<template>
    <div class="app-container">
        <el-form :model="banner" :rules="rules" ref="ruleForm" label-width="200px" class="demo-ruleForm">
            <el-form-item label="Banner链接URL" prop="bannerUrl" >
                <el-input v-model="banner.bannerUrl"></el-input>
            </el-form-item>
            <el-form-item label="显示排序" prop="orderNum" >
                <el-input-number v-model="banner.orderNum" :min="1" :max="999" label="排序号"></el-input-number>
            </el-form-item>
            <el-form-item class="myuploader" label="Banner图片" prop="bannerImg" >
                <el-upload
                ref="uploader"
                class="upload-demo"
                :on-change="handleChange"
                :action="uploadUrl"
                :file-list="fileList"
                :data="banner"
                :multiple="false"
                :auto-upload="false"
                :http-request="uploadSectionFile"
                list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            </el-form-item>
        </el-form>
    </div>
    
</template>

<script>
  import { updateBannerApi } from '@/api/banner'
  import { getBannerApi } from '@/api/banner'
  export default {
    data() {
      return {
        changeBannerImg: false,
        imgPath:process.env.VUE_APP_BASE_API,
        fileList:[],
        uploadUrl:process.env.VUE_APP_BASE_API+'/banner',
        banner: {
        },
        rules: {
          bannerUrl: [
            { required: true, message: '请输入Banner链接URL', trigger: 'blur' }
          ],
          orderNum: [
            { required: true, message: '请输入排序号', trigger: 'blur' }
          ]
        }
      }
    },
    created() {
      this.banner.id = this.$route.params.id
      this.getBanner(this.banner.id)
    },
    methods: {
      getBanner(id) {
        getBannerApi(id)
          .then(response=>{
            this.banner = response.data
            this.fileList=[{name: this.banner.bannerImg.substring(this.banner.bannerImg.lastIndexOf("/")+1), url:this.imgPath + this.banner.bannerImg, status: "ready"}]
            delete this.banner.createTime
          })
      },
      uploadSectionFile(params) {
          const file = params.file,
            fileType = file.type,
            isImage = fileType.indexOf("image") != -1,
            isLt2M = file.size / 1024 / 1024 < 2
          // 这里常规检验，看项目需求而定
          if (!isImage) {
            this.$message.error("只能上传图片格式png、jpg、gif!")
            return
          }
          if (!isLt2M) {
            this.$message.error("只能上传图片大小小于2M")
            return
          }
          // 根据后台需求数据格式
          const form = new FormData()
          // 文件对象
          form.append("file", file)
          //遍历banner转formdata格式键值对
          delete this.banner.bannerImg
          Object.keys(this.banner).forEach((key) => {
           form.append(key, this.banner[key])
          })
          this.updateBanner(form);
      },
      updateBanner(form) {
        updateBannerApi(form)
            .then(res => {
              if(res.status == 0){
                this.$message('提交成功')
              }
              this.$router.push('/content/banner')
            })
      },
      handleChange(file, fileList) {
        console.log(file);
        const isPNG = file.raw.type === "image/png"
        const isLt2M = file.raw.size / 1024 / 1024 < 0.5
        if (fileList.length > 0) {
        //单个覆盖上传
            this.fileList = [fileList[fileList.length - 1]] // 这一步，是 展示最后一次选择的csv文件
            if (!isPNG) {
                this.$message.error("上传图片只能是 PNG 格式!")
                this.fileList = []
                return false
            } else if (!isLt2M) {
                this.$message.error("上传图片大小不能超过 200kb!")
                this.fileList = []
                return false
            }
            this.changeBannerImg = true
            return true
        }
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(this.changeBannerImg){
              this.$refs.uploader.submit()
            }else{
              var formData = new FormData()
              Object.keys(this.banner).forEach((key) => {
               formData.append(key, this.banner[key])
              }) 
              this.updateBanner(formData)
            }
          } 
        })
      }
    }
  }
</script>

<style scoped>
    .myuploader >>> .el-list-enter-active,.myuploader >>> .el-list-leave-active{
        transition: none;
    }

    .myuploader >>>.el-list-enter,.myuploader >>> .el-list-leave-active {
      opacity: 0;
    }
</style>